import os
import pickle
from gevent import monkey
monkey.patch_all()      # 用于将标准库中大部分阻塞式调用修改为协作式运行
import gevent

from Base import SockerBase


class Sender:
    MAX_SIZE = 1024*512

    def __init__(self, conn):
        self.conn = SockerBase(conn=conn)

    def send_file_next_part(self):
        with open(self.path, 'rb') as f:
            self.conn.conn.sendall(self.conn.ge)
            datas = pickle.dumps(f.read())
            for i in range(0, len(datas), self.MAX_SIZE):
                data = datas[i:i+self.MAX_SIZE]
                if len(data) == self.MAX_SIZE:
                    self.conn.conn.sendall(data)
                    yield True
                else:
                    self.conn.conn.sendall(data)
                    self.conn.conn.sendall(self.conn.ge)
                    self.conn.print('Send file successfully')
                    yield False
            # else:
            #     self.conn.conn.sendall(data)
            #     self.conn.conn.sendall(self.conn.ge)
            #     self.conn.print('Send file successfully')
            #     yield False

    def send_check(self):
        self.request = self.conn.myrece()
        self.path = self.request.get('path', 'None')
        if self._check_file():
            self.conn.mysend({'able': True})
            return True
        else:
            self.conn.mysend({'able': False})
            return False

    def _check_file(self):
        if not os.path.exists(self.path):
            self.conn.print('File does not exit')
            return False
        else:
            return True


class Server:
    """ 初始化 启动"""
    def __init__(self, port=50000):
        self.sock = SockerBase(port=port)
        # self.sock.socket.setblocking(False)
        self.sock.socket.settimeout(1)
        self.sock.init_server(10)
        self.sender_line = []

    def start(self):
        while True:
            try:
                # self.sock.print('Before listen')
                conn = self.sock.start_listen()
                self.sock.print('Before request')
                self.push_conn(conn)
                # gevent.sleep(0.5)
            except:
                pass
            finally:
                self.poll_send()

    def push_conn(self, conn):
        sender = Sender(conn)
        if sender.send_check():
            self.sock.print('Accept request')
            self.sender_line.append(sender.send_file_next_part())
        else:
            self.sock.print('Refuse request')

    def poll_send(self):
        # print(self.sender_line)
        for sender in self.sender_line:
            if not next(sender):
                self.sock.print('Remove sender')
                self.sender_line.remove(sender)
            # else:
            #     self.sender_line.remove(sender)

if __name__ == '__main__':
    s = Server()
    s.start()